package j2se.Datagram;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Created by jingqing.zhou on 2015/6/17.
 * 服务器端，实现基于udp的用户登录
 */
public class UDPServer {
    public static void main(String[] args) throws IOException {

        //创建服务器端datagramSocket ，指定端口
        DatagramSocket socket = new DatagramSocket(8999);

        //封装一个空的数据报，用于接收客户端的数据报
        byte[] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data,data.length);

        socket.receive(packet);//阻塞，等待接收客户端的数据，并封装到packet的data中

        String info = new String(data,0,packet.getLength());

        System.out.println("服务器说： 客户端信息：" +info);

        /**
         * 向客户端响应数据
         */
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        byte[] data2 = "欢迎您!".getBytes();

        DatagramPacket packet2 = new DatagramPacket(data2,data2.length,address,port);
        socket.send(packet2);

        socket.close();
    }
}
